<template>
	<view class="detail-page">
		<swiper class="gallery" circular indicator-dots :autoplay="galleryList.length > 1">
			<swiper-item v-for="(img, idx) in galleryList" :key="idx">
				<image class="gallery-image" :src="img" mode="aspectFill" />
			</swiper-item>
		</swiper>

		<view class="info-card">
			<view class="title-row">
				<text class="title">{{ product.title }}</text>
				<view class="tags" v-if="tagList.length">
					<text class="tag" v-for="tag in tagList" :key="tag">{{ tag }}</text>
				</view>
			</view>
			<view class="price-row">
				<text class="price">¥{{ product.price }}</text>
				<text v-if="product.originalPrice" class="origin">¥{{ product.originalPrice }}</text>
			</view>
			<text v-if="product.subTitle" class="sub">{{ product.subTitle }}</text>
			<view class="meta-row">
				<text>销量 {{ product.sales || 0 }}</text>
				<text>库存 {{ product.stock || 0 }}</text>
			</view>
		</view>

		<view class="section" v-if="specList.length">
			<view class="section-title">商品规格</view>
			<view class="spec-list">
				<view class="spec-item" v-for="spec in specList" :key="spec.label">
					<text class="spec-label">{{ spec.label }}</text>
					<text class="spec-value">{{ spec.value }}</text>
				</view>
			</view>
		</view>

		<view class="section" v-if="product.detail">
			<view class="section-title">图文详情</view>
			<rich-text :nodes="product.detail"></rich-text>
		</view>

		<view class="section" v-if="product.nutrition">
			<view class="section-title">营养信息</view>
			<text class="section-text">{{ product.nutrition }}</text>
		</view>

		<view class="section" v-if="product.shippingInfo">
			<view class="section-title">配送与售后</view>
			<text class="section-text">{{ product.shippingInfo }}</text>
		</view>

		<view class="section" v-if="reviews.length">
			<view class="section-title">用户评价</view>
			<view class="review" v-for="r in reviews" :key="r.id">
				<view class="row">
					<text class="stars">{{ '★★★★★'.slice(0, r.rating || 5) }}</text>
					<text class="time">{{ formatTime(r.createdAt) }}</text>
				</view>
				<text class="content">{{ r.content || '（无文字评价）' }}</text>
			</view>
		</view>

		<view class="bottom-bar">
			<view class="fav-btn" :class="{active:isFavorite}" @click="toggleFavorite">
				<image class="fav-icon" :src="isFavorite ? '/static/assets/icons/favor_fill.png' : '/static/assets/icons/favor.png'" mode="aspectFit"></image>
				<text class="fav-text">{{ isFavorite ? '已收藏' : '收藏' }}</text>
			</view>
			<button class="btn add" @click="addToCart">加入购物车</button>
			<button class="btn buy" @click="buyNow">立即购买</button>
		</view>
	</view>
</template>

<script>
import { api } from '../../utils/request.js'
import { BASE_URL } from '../../utils/server.js'

export default {
	data() {
		return {
			product: {},
			galleryList: [],
			tagList: [],
			specList: [],
			isFavorite: false,
			reviews: []
		}
	},
	onLoad(query) {
		if (query && query.id) {
			this.load(query.id);
		}
	},
	methods: {
		async load(id) {
			try {
				const res = await api.getProduct(id);
				if (res.code === 0) {
					this.product = res.data || {};
					this.prepareDerived();
					this.checkFavorite();
					this.loadReviews();
				} else {
					uni.showToast({ icon: 'none', title: res.message || '加载失败' });
				}
			} catch (err) {
				uni.showToast({ icon: 'none', title: '请求失败' });
			}
		},
		async checkFavorite(){
			if(!this.product.id) return;
			try{
				const r = await api.checkFavorite(this.product.id);
				if(r.code===0){ this.isFavorite = !!r.data; }
			}catch{}
		},
		async toggleFavorite(){
			if(!this.product.id) return;
			try{
				if(this.isFavorite){
					const r = await api.removeFavorite(this.product.id);
					if(r.code===0){ this.isFavorite=false; uni.showToast({title:'已取消收藏'}); }
					else { uni.showToast({icon:'none', title:r.message||'操作失败'}); }
				}else{
					const r = await api.addFavorite(this.product.id);
					if(r.code===0){ this.isFavorite=true; uni.showToast({title:'已收藏'}); }
					else { uni.showToast({icon:'none', title:r.message||'操作失败'}); }
				}
			}catch(e){ uni.showToast({icon:'none', title:'请求失败'}); }
		},
		prepareDerived() {
			this.galleryList = this.parseGallery(this.product.galleryImages, this.product.coverImage);
			this.tagList = this.product.tags ? this.product.tags.split(/[,，]/).filter(Boolean) : [];
			this.specList = this.buildSpecs();
		},
		parseGallery(images, cover) {
			if (!images && !cover) {
				return ['/static/logo.png'];
			}
			let list = [];
			if (images) {
				try {
					const parsed = JSON.parse(images);
					if (Array.isArray(parsed)) list = parsed;
				} catch (e) {
					list = images.split(',').map(s => s.trim()).filter(Boolean);
				}
			}
			if (cover) {
				list.unshift(cover);
			}
			// 处理图片URL，拼接BASE_URL
			return list.length ? Array.from(new Set(list)).map(url => this.getImageUrl(url)) : ['/static/logo.png'];
		},
		getImageUrl(url) {
			if (!url) return '/static/logo.png';
			if (url.startsWith('http')) return url;
			return BASE_URL + url;
		},
		buildSpecs() {
			const result = [];
			const mapping = [
				{ label: '产地', value: this.product.origin },
				{ label: '净含量', value: this.product.weight },
				{ label: '单位', value: this.product.unit },
				{ label: '贮存方式', value: this.product.storageInfo }
			];
			mapping.forEach(item => {
				if (item.value) {
					result.push(item);
				}
			});
			return result;
		},
		async addToCart() {
			if (!this.product.id) return;
			try {
				const res = await api.cartAdd({ productId: this.product.id, quantity: 1 });
				if (res.code === 0) {
					uni.showToast({ title: '已加入购物车' });
				} else {
					uni.showToast({ icon: 'none', title: res.message || '添加失败' });
				}
			} catch (err) {
				uni.showToast({ icon: 'none', title: '操作失败' });
			}
		},
		async buyNow() {
			if (!this.product.id) return;
			// 立即购买不加入购物车，直接跳转到订单确认页
			const query = `type=single&productId=${this.product.id}&quantity=1`;
			uni.navigateTo({ url: `/pages/order/confirm?${query}` });
		},
		async loadReviews(){
			try{ const r = await api.getProductReviews(this.product.id, { pageNum:1, pageSize:5 }); if(r.code===0){ this.reviews = r.data||[]; } }catch{}
		},
		formatTime(t){ if(!t) return ''; try{ return t.replace('T',' ').substring(0,16); }catch{ return t; } }
	}
}
</script>

<style>
.detail-page { padding-bottom: 140rpx; background: #F0F7FF; min-height: 100vh; }
/* #ifdef MP-WEIXIN */
.detail-page { padding-bottom: calc(160rpx + env(safe-area-inset-bottom)); }
/* #endif */
.gallery { height: 560rpx; background: #fff; }
.gallery-image { width: 100%; height: 100%; }
.info-card { background: #fff; margin: 0 24rpx 24rpx; padding: 28rpx; border-radius: 24rpx; box-shadow: 0 8rpx 24rpx rgba(91,155,213,.1); }
.title-row { display: flex; justify-content: space-between; align-items: flex-start; gap: 20rpx; }
.title { font-size: 36rpx; font-weight: 700; color: #2C5F8D; flex: 1; }
.tags { display: flex; flex-wrap: wrap; gap: 12rpx; }
.tag { background: rgba(91,155,213,.15); color: #5B9BD5; padding: 6rpx 16rpx; border-radius: 999rpx; font-size: 22rpx; }
.price-row { display: flex; align-items: baseline; gap: 16rpx; margin: 16rpx 0; }
.price { font-size: 44rpx; color: #FF4D4F; font-weight: 700; }
.origin { font-size: 24rpx; color: #8FA8C4; text-decoration: line-through; }
.sub { font-size: 26rpx; color: #6B8BA8; display: block; margin-bottom: 16rpx; }
.meta-row { display: flex; gap: 24rpx; font-size: 24rpx; color: #8FA8C4; }
.section { background: #fff; margin: 0 24rpx 24rpx; padding: 28rpx; border-radius: 24rpx; box-shadow: 0 8rpx 24rpx rgba(91,155,213,.08); }
.section-title { font-size: 32rpx; font-weight: 600; margin-bottom: 20rpx; color: #2C5F8D; }
.section-text { color: #4A6FA5; font-size: 26rpx; line-height: 1.6; }
.spec-list { display: grid; grid-template-columns: repeat(2,1fr); gap: 18rpx; }
.spec-item { display: flex; flex-direction: column; padding: 16rpx 20rpx; background: #E8F2FF; border-radius: 16rpx; }
.spec-label { font-size: 24rpx; color: #8FA8C4; }
.spec-value { font-size: 28rpx; color: #2C5F8D; margin-top: 8rpx; }
.bottom-bar { position: fixed; left: 0; right: 0; bottom: env(safe-area-inset-bottom); display: flex; gap: 16rpx; padding: 20rpx 24rpx calc(20rpx + env(safe-area-inset-bottom)); background: rgba(255,255,255,.98); box-shadow: 0 -8rpx 24rpx rgba(91,155,213,.12); }
/* #ifdef MP-WEIXIN */
.bottom-bar { bottom: 0; padding-bottom: calc(20rpx + env(safe-area-inset-bottom)); }
/* #endif */
.fav-btn { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 0 20rpx; border: 2rpx solid #5B9BD5; border-radius: 16rpx; background:#fff; min-width: 100rpx; }
.fav-btn.active { background:#E8F2FF; border-color: #5B9BD5; }
.fav-icon { width: 40rpx; height: 40rpx; margin-bottom: 4rpx; }
.fav-text { font-size: 22rpx; color: #5B9BD5; }
.btn { flex: 1; padding: 20rpx 0; border-radius: 18rpx; color: #fff; font-size: 30rpx; }
.btn.add { background: linear-gradient(135deg,#FF6B6B,#FF8787); }
.btn.buy { background: linear-gradient(135deg,#FF4D4F,#FF6B6B); }
.review{ padding: 10rpx 0; border-top: 2rpx solid #E8F2FF; }
.review:first-child{ border-top: 0; }
.stars{ color:#FFD700; font-size: 26rpx; }
.time{ color:#8FA8C4; font-size: 22rpx; margin-left: auto; }
.content{ display:block; color:#4A6FA5; font-size: 26rpx; margin-top: 6rpx; }
</style>